<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useUserStoreHook } from "@/store/modules/user";
import { initRouter, getTopMenu } from "@/router/utils";
import { updateTokenApi } from "@/api/user";
import {
  bg,
  bgnew,
  bgleft,
  avatar,
  illustration,
  favicon,
} from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ReImageVerify } from "@/components/ReImageVerify";
import {
  ref,
  reactive,
  toRaw,
  onMounted,
  onBeforeUnmount,
  watch,
  onBeforeMount,
  nextTick,
} from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { setToken } from "@/utils/auth";
import { addPathMatch } from "@/router/utils";
import { usePermissionStoreHook } from "@/store/modules/permission";

import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import { config } from "process";
import { func } from "vue-types";

defineOptions({
  name: "Login",
});
import verImg from "@/assets/login/ver.png";
const verImgEnd = ref("/api/user/getverifycode");
//刷新验证码
const verImgRefresh = ref(0);
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const imgCode = ref("");
const placeholderVer = "请输入验证码";

const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();

const ruleForm = reactive({
  username: "",
  password: "",
  verifyCode: "",
});

function setVerImgRefresh() {
  verImgEnd.value = "/api/user/getverifycode?random=" + new Date().getTime();
}

//formEl是个ref实例
const onLogin = async (formEl: FormInstance | undefined) => {
  console.log("formEl", formEl);

  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("valid", valid);
      console.log("ruleForm", ruleForm);
      useUserStoreHook()
        .loginByUsername({
          username: ruleForm.username,
          password: ruleForm.password,
          verifyCode: ruleForm.verifyCode,
        })
        .then((res) => {
          console.log(res.message);
          if (res.code === 2000) {
            //设置本地登录成功标识
            const roles = res.data.roles;
            const username = res.data.username;
            const description = res.data.description;
            setToken({
              username: username,
              roles: [roles],
              accessToken: res.data.token,
              description: description,
            } as any);
            // 全部采取静态路由模式
            usePermissionStoreHook().handleWholeMenus([]);
            addPathMatch();
            if (roles === "admin") {
              router.push("/");
            } else {
              router.push("/assetmg/ipgroup");
            }
            message("登录成功", { type: "success" });

            // 登录成功后获取设备token
            handleGetDeviceTokens();
          } else {
            /* empty */
            message(res.message, { type: "error" });
            loading.value = false;
            setVerImgRefresh();
            return fields;
          }
        })
        .catch((err) => {
          loading.value = false;
          setVerImgRefresh();
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

// 获取设备token的方法
const handleGetDeviceTokens = async () => {
  try {
    const response = await updateTokenApi();

    if (
      response &&
      response.data &&
      Array.isArray(response.data) &&
      response.data.length > 0
    ) {
      const tokenData = response.data[0];

      if (tokenData.main_device_token && tokenData.sub_device_token) {
        localStorage.setItem("token175", tokenData.main_device_token);
        localStorage.setItem("token43", tokenData.sub_device_token);
        localStorage.setItem("tokenData", JSON.stringify(tokenData));
        console.log("设备Token获取成功");
      }
    }
  } catch (error) {
    console.error("获取设备Token失败:", error);
  }
};

onBeforeMount(() => {
  return;
  // 获取验证码
  useUserStoreHook()
    .getVerifyCode()
    .then((res) => {
      if (res.success) {
        console.log("verimgurl", res.data.verifyCodeUrl);
        useUserStoreHook().SET_VERIFYCODE(res.data.verifyCode);
      }
    });
});

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

watch(imgCode, (value) => {
  console.log("imgCCode", value);
  useUserStoreHook().SET_VERIFYCODE(value);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bgnew" class="wave newimgbg" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
        v-show="false"
      />
    </div>
    <div class="login-container-box">
      <div class="login-container login-container-new">
        <div class="img">
          <!-- <component :is="toRaw(illustration)" /> -->
          <img :src="bgleft" class="bgleft" />
        </div>
        <div class="login-box login-box-new">
          <div class="login-form">
            <avatar class="avatar" />
            <!-- <img :src="favicon" class="favicon" /> -->
            <Motion>
              <h2 class="outline-none">{{ title }}</h2>
            </Motion>

            <el-form
              ref="ruleFormRef"
              :model="ruleForm"
              :rules="loginRules"
              size="large"
            >
              <Motion :delay="100">
                <el-form-item
                  :rules="[
                    {
                      required: true,
                      message: '请输入账号',
                      trigger: 'blur',
                    },
                  ]"
                  prop="username"
                >
                  <el-input
                    clearable
                    v-model="ruleForm.username"
                    placeholder="账号"
                    :prefix-icon="useRenderIcon(User)"
                  />
                </el-form-item>
              </Motion>

              <Motion :delay="150">
                <el-form-item prop="password">
                  <el-input
                    clearable
                    show-password
                    v-model="ruleForm.password"
                    placeholder="密码"
                    :prefix-icon="useRenderIcon(Lock)"
                  />
                </el-form-item>
              </Motion>

              <Motion :delay="200">
                <el-form-item prop="verifyCode">
                  <!-- @keyup.enter.stop="onLogin(ruleFormRef)" -->
                  <el-input
                    v-model="ruleForm.verifyCode"
                    clearable
                    maxlength="4"
                    :placeholder="placeholderVer"
                    :prefix-icon="useRenderIcon('ri:shield-keyhole-line')"
                  >
                    <template v-slot:append>
                      <!-- <ReImageVerify v-model:code="imgCode" /> -->
                      <img
                        :src="verImgEnd"
                        :key="verImgRefresh"
                        alt=""
                        @click="setVerImgRefresh()"
                        class="vrcode"
                      />
                    </template>
                  </el-input>
                </el-form-item>
              </Motion>

              <Motion :delay="250">
                <el-button
                  class="w-full mt-4"
                  size="default"
                  type="primary"
                  :loading="loading"
                  @click="onLogin(ruleFormRef)"
                >
                  登录
                </el-button>
              </Motion>
            </el-form>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.login-container-box {
  display: flex;
  align-items: center;
  height: 100vh;
}

.login-container-new {
  grid-gap: 0;
  height: 500px;
  width: 1100px;
  margin: 0 auto;
}

.newimgbg {
  position: fixed;
  height: 100%;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100%;
  z-index: -1;
}

.bgleft {
  width: 100% !important;
  height: 100% !important;
}

.favicon {
  width: 80px;
  height: 80px;
  margin: 0 auto;
  display: block;
}

.login-box-new {
  justify-content: center;
  background: white;
}

@media screen and (max-width: 1180px) {
  .login-container-new {
    height: 500px;
  }
}

.vrcode {
  width: 120px;
  height: 38px;
  border: none;
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
}
</style>
